#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <gtk/gtk.h>

#define MAXSIZE 100

char* ipmid = "192.168.232.129";
extern char* filename; //需要发送文件的文件名
//extern GtkTextBuffer* rcv_buffer; //文本框缓存区

void FileSend()
{
    int i;
    int fp;
    int res;
    int fsend_sockfd;
    char buffer;
    struct sockaddr_in  fsend_address;
    struct stat filesize;
    //GtkTextIter start;
    //GtkTextIter end;

    //设置sockaddr_in结构体中的相关参数
    fsend_address.sin_family = AF_INET;
    fsend_address.sin_addr.s_addr = inet_addr(ipmid);
    fsend_address.sin_port = htons(5050);

    //创建socket
    if ((fsend_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }
	
    //用connect函数建立连接 
    if (connect(fsend_sockfd, (struct sockaddr*)&fsend_address, sizeof(struct sockaddr)) == -1)
    {
        perror("connect");
        exit(EXIT_FAILURE);
    }

    //打开文件 
    
    if ((fp = open(filename, O_RDONLY)) == -1)
    {
        perror("send file open");
        exit(EXIT_FAILURE);
    }

    //获取接收方文件长度
    if ((res = stat(filename, &filesize)) != 0)
    {
        perror("stat");
        exit(EXIT_FAILURE);
    }

    //发送文件名
    if ((res = send(fsend_sockfd, filename, MAXSIZE, 0)) < 0)
    {
        perror("sendfilename");
        exit(EXIT_FAILURE);
    }

    //发送文件长度
    if ((res = send(fsend_sockfd, &filesize.st_size, 2, 0)) < 0)
    {
        perror("sendfilesize");
        exit(EXIT_FAILURE);
    }

    //gtk_text_buffer_get_bounds(GTK_TEXT_BUFFER(rcv_buffer), &start, &end);//调整缓冲区指针开始和结束的位置
    //gtk_text_buffer_insert(GTK_TEXT_BUFFER(rcv_buffer), &end, "********Waiting********\n", -1);//向缓冲区插入文字start，end分别为文本框文字开始位置和结束位置的iter，len是要插入文本的长度，可以是-1，表示插入text的所有内容。

    //发送文件
    i = 0;
    while (i < filesize.st_size)
    {
        read(fp, &buffer, 1);
        if ((res = send(fsend_sockfd, &buffer, 1, 0)) < 0)
        {
            perror("send");
            break;
        }
        i++;
    }

printf("aaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
    //gtk_text_buffer_get_bounds(GTK_TEXT_BUFFER(rcv_buffer), &start, &end);

   /* //判断文件传送正确与否
    if (i == filesize.st_size)
        gtk_text_buffer_insert(GTK_TEXT_BUFFER(rcv_buffer), &end,
            "********Transfer successful!*********\n", -1);
    else
        gtk_text_buffer_insert(GTK_TEXT_BUFFER(rcv_buffer), &end,
            "********Transfer failed!**********\n", -1);*/

    //关闭文件
    close(fp);
    close(fsend_sockfd);
}
